const model = require('./model')
const { genToken, verifyToken } = require('./utils/token.js')

exports.login = async (req, res) => {
  let { username, password } = req.body
  // 真实业务中，肯定要去数据库中匹配
  let findUser = await model.Login(username, password)
  if (findUser.length > 0) {
    // 找到了，要生成JWT用户登录态（token字符串），返回给前端
    let token = genToken(
      { id: findUser[0].id, username: findUser[0].username },
      '15000ms'
    )
    let refreshToken = genToken(
      { id: findUser[0].id, username: findUser[0].username },
      '15d'
    )
    res.json({
      message: '登录成功',
      data: { token, refreshToken },
      code: 20000,
    })
  } else {
    res.json({ message: '用户名或密码错误', code: 200001 })
  }
}

exports.refreshToken = async (req, res) => {
  let { refreshToken } = req.body

  // 1. 验证refreshToken中的有效期
  let userInfo = verifyToken(refreshToken)
  if (userInfo === false) {
    // refreshToken失效了
    res.status(401).json({ message: '用户refreshToken刷新失败' })
    return
  }
  // 2. 获取refreshToken中的用户信息,要去数据库查询最新的用户信息
  let result = await model.getUserInfoById(userInfo.id)
  if (result.length > 0) {
    let token = genToken(
      { id: result[0].id, username: result[0].username },
      '15000ms'
    )
    // 3. 重新再生成新token并返回给前端
    res.json({
      message: '刷新token成功',
      data: { token },
      code: 20000,
    })
  } else {
    res.json({
      message: '用户信息有误',
      code: 20003,
    })
  }
}

exports.order = async (req, res) => {
  // token有效,要获取token中用户的id去查询相应的订单信息
  let user_id = req.user_id
  let orderData = await model.getOrderData(user_id)
  res.json(orderData)
}

exports.address = (req, res) => {
  // console.log('user_id=>', req.user_id)
  let user_id = req.user_id
  let order = model.getAddressData()
  res.json(order)
}
